import '../utils/http/http_client.dart';
import '../models/device_model.dart';
import 'dart:convert';
import 'package:dio/dio.dart';

/// 设备服务提供者
class DeviceProvider {
  final HttpClient _httpClient = HttpClient();

  /// 获取设备列表
  /// 
  /// [pageNum] 页码，默认为1
  /// [pageSize] 每页记录数，默认为10
  /// [deviceName] 设备名称（可选）
  /// [deviceSn] 设备序列号（可选）
  /// [productKey] 产品标识码（可选）
  /// [status] 设备状态(0:未激活 1:在线 2:离线 3:禁用)（可选）
  /// [beginTime] 开始时间（可选）
  /// [endTime] 结束时间（可选）
  Future<DeviceListResponse> getDeviceList({
    int pageNum = 1,
    int pageSize = 10,
    String? deviceName,
    String? deviceSn,
    String? productKey,
    int? status,
    String? beginTime,
    String? endTime,
  }) async {
    try {
      final Map<String, dynamic> params = {
        'pageNum': pageNum,
        'pageSize': pageSize,
      };
      
      // 添加可选参数
      if (deviceName != null && deviceName.isNotEmpty) {
        params['deviceName'] = deviceName;
      }
      if (deviceSn != null && deviceSn.isNotEmpty) {
        params['deviceSn'] = deviceSn;
      }
      if (productKey != null && productKey.isNotEmpty) {
        params['productKey'] = productKey;
      }
      if (status != null) {
        params['status'] = status;
      }
      if (beginTime != null && beginTime.isNotEmpty) {
        params['beginTime'] = beginTime;
      }
      if (endTime != null && endTime.isNotEmpty) {
        params['endTime'] = endTime;
      }
      
      final response = await _httpClient.get(
        '/device/device/list',
        params: params,
      );
      
      // 打印设备列表中第一个设备的wvpDeviceId字段
      if (response['rows'] != null && response['rows'].isNotEmpty) {
        print('【设备列表第一个设备】');
        print('deviceId: ${response['rows'][0]['deviceId']}');
        print('deviceName: ${response['rows'][0]['deviceName']}');
        print('wvpDeviceId: ${response['rows'][0]['wvpDeviceId']}');
        print('deviceSn: ${response['rows'][0]['deviceSn']}');
      }
      
      return DeviceListResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取设备详情
  /// 
  /// [deviceId] 设备ID
  Future<DeviceDetailResponse> getDeviceDetail(int deviceId) async {
    try {
      final response = await _httpClient.get('/device/device/$deviceId');
      
      // 打印原始响应数据
      print('【设备详情原始数据】deviceId=$deviceId');
      print('【设备详情原始数据】response=$response');
      
      // 如果有data字段，打印其中的wvpDeviceId
      if (response['data'] != null) {
        print('【设备详情wvpDeviceId】${response['data']['wvpDeviceId']}');
      }
      
      return DeviceDetailResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 通过设备序列号查询设备
  /// 
  /// [deviceSn] 设备序列号
  Future<DeviceDetailResponse> getDeviceBySn(String deviceSn) async {
    try {
      final response = await _httpClient.get('/device/sn/$deviceSn');
      return DeviceDetailResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取设备统计信息
  Future<DeviceStatsResponse> getDeviceStats() async {
    try {
      // 由于stats接口不可用，我们手动构建统计信息
      final deviceList = await getDeviceList(pageNum: 1, pageSize: 100);
      
      int totalCount = deviceList.total;
      int onlineCount = 0;
      int offlineCount = 0;
      int inactiveCount = 0;
      int disabledCount = 0;
      
      // 遍历设备列表，统计不同状态的设备数量
      for (var device in deviceList.rows) {
        if (device.status == 1) { // 在线
          onlineCount++;
        } else if (device.status == 2) { // 离线
          offlineCount++;
        } else if (device.status == 0) { // 未激活
          inactiveCount++;
        } else if (device.status == 3) { // 禁用
          disabledCount++;
        }
      }
      
      // 构造返回数据
      return DeviceStatsResponse(
        code: 200,
        msg: "操作成功",
        data: DeviceStats(
          totalCount: totalCount,
          onlineCount: onlineCount,
          offlineCount: offlineCount,
          inactiveCount: inactiveCount,
          disabledCount: disabledCount,
          todayActivated: 0,
          weekActivated: 0
        )
      );
    } catch (e) {
      rethrow;
    }
  }
  
  /// 根据产品ID查询设备列表
  /// 
  /// [productId] 产品ID
  /// [pageNum] 页码，默认为1
  /// [pageSize] 每页记录数，默认为10
  Future<DeviceListResponse> getDevicesByProductId(
    int productId, {
    int pageNum = 1,
    int pageSize = 10,
  }) async {
    try {
      final Map<String, dynamic> params = {
        'pageNum': pageNum,
        'pageSize': pageSize,
      };
      
      final response = await _httpClient.get(
        '/device/product/$productId',
        params: params,
      );
      
      return DeviceListResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取设备最新状态
  /// 
  /// [deviceSn] 设备序列号
  Future<DeviceDetailResponse> getDeviceLatestStatus(String deviceSn) async {
    try {
      final response = await _httpClient.get('/device/status/latest/$deviceSn');
      return DeviceDetailResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 新增设备
  /// 
  /// [deviceName] 设备名称
  /// [deviceSn] 设备序列号
  /// [productId] 产品ID
  /// [nodeType] 节点类型(1:直连设备 2:网关设备 3:子设备)
  /// [location] 位置描述（可选）
  /// [longitude] 经度（可选）
  /// [latitude] 纬度（可选）
  /// [tags] 标签(多个以逗号分隔)（可选）
  Future<void> addDevice({
    required String deviceName,
    required String deviceSn,
    required int productId,
    required int nodeType,
    String? location,
    double? longitude,
    double? latitude,
    String? tags,
  }) async {
    try {
      final Map<String, dynamic> data = {
        'deviceName': deviceName,
        'deviceSn': deviceSn,
        'productId': productId,
        'nodeType': nodeType,
      };
      
      // 添加可选参数
      if (location != null && location.isNotEmpty) {
        data['location'] = location;
      }
      if (longitude != null) {
        data['longitude'] = longitude;
      }
      if (latitude != null) {
        data['latitude'] = latitude;
      }
      if (tags != null && tags.isNotEmpty) {
        data['tags'] = tags;
      }
      
      await _httpClient.post(
        '/device',
        data: data,
      );
    } catch (e) {
      rethrow;
    }
  }
  
  /// 修改设备
  /// 
  /// [deviceId] 设备ID
  /// [deviceName] 设备名称（可选）
  /// [location] 位置描述（可选）
  /// [longitude] 经度（可选）
  /// [latitude] 纬度（可选）
  /// [tags] 标签(多个以逗号分隔)（可选）
  /// [deviceImage] 设备图片URL（可选）
  Future<void> updateDevice({
    required int deviceId,
    String? deviceName,
    String? location,
    double? longitude,
    double? latitude,
    String? tags,
    String? deviceImage,
  }) async {
    try {
      final Map<String, dynamic> data = {
        'deviceId': deviceId,
      };
      
      // 添加可选参数
      if (deviceName != null && deviceName.isNotEmpty) {
        data['deviceName'] = deviceName;
      }
      if (location != null && location.isNotEmpty) {
        data['location'] = location;
      }
      if (longitude != null) {
        data['longitude'] = longitude;
      }
      if (latitude != null) {
        data['latitude'] = latitude;
      }
      if (tags != null && tags.isNotEmpty) {
        data['tags'] = tags;
      }
      if (deviceImage != null && deviceImage.isNotEmpty) {
        data['deviceImage'] = deviceImage;
      }
      
      await _httpClient.put(
        '/device',
        data: data,
      );
    } catch (e) {
      rethrow;
    }
  }
  
  /// 上传设备图片
  /// 
  /// [deviceId] 设备ID
  /// [imagePath] 图片本地路径
  Future<String> uploadDeviceImage(int deviceId, String imagePath) async {
    try {
      // 创建FormData对象
      final formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(
          imagePath,
          filename: 'device_image_$deviceId.jpg',
        ),
      });
      
      // 上传图片
      final response = await _httpClient.post(
        '/common/upload',
        data: formData,
      );
      
      if (response is Map<String, dynamic> && 
          response.containsKey('url') && 
          response['url'] is String) {
        final String imageUrl = response['url'];
        
        // 更新设备信息，设置图片URL
        await updateDevice(
          deviceId: deviceId,
          deviceImage: imageUrl,
        );
        
        return imageUrl;
      } else {
        throw Exception('上传图片失败，无效的响应格式');
      }
    } catch (e) {
      print('上传设备图片失败: $e');
      rethrow;
    }
  }
  
  /// 删除设备
  /// 
  /// [deviceIds] 设备ID数组
  Future<void> deleteDevices(List<int> deviceIds) async {
    try {
      await _httpClient.delete('/device/${deviceIds.join(",")}');
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取设备总数
  Future<int> getDeviceCount() async {
    try {
      final response = await getDeviceList(pageNum: 1, pageSize: 1);
      return response.total;
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取在线设备数
  Future<int> getOnlineDeviceCount() async {
    try {
      final stats = await getDeviceStats();
      return stats.data?.onlineCount ?? 0;
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取离线设备数
  Future<int> getOfflineDeviceCount() async {
    try {
      final stats = await getDeviceStats();
      return stats.data?.offlineCount ?? 0;
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取主页所需统计数据
  /// 
  /// 返回设备总数、在线设备数和离线设备数
  Future<Map<String, int>> getHomeStatistics() async {
    try {
      // 改为获取本地数据，避免依赖可能不可用的API
      int totalCount = 0;
      int onlineCount = 0;
      int offlineCount = 0;
      int inactiveCount = 0;
      int disabledCount = 0;
      
      try {
        totalCount = await getDeviceCount();
      } catch (e) {
        // 如果获取失败，使用默认值
      }
      
      try {
        // 尝试获取设备统计数据
        final stats = await getDeviceStats();
        onlineCount = stats.data?.onlineCount ?? 0;
        offlineCount = stats.data?.offlineCount ?? 0;
        inactiveCount = stats.data?.inactiveCount ?? 0;
        disabledCount = stats.data?.disabledCount ?? 0;
      } catch (e) {
        // 如果获取失败，使用默认值
      }
      
      return {
        'totalCount': totalCount,
        'onlineCount': onlineCount,
        'offlineCount': offlineCount,
        'inactiveCount': inactiveCount,
        'disabledCount': disabledCount,
      };
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取设备属性历史数据
  /// 
  /// [deviceSn] 设备序列号
  /// [startTime] 开始时间戳(毫秒)，可选
  /// [endTime] 结束时间戳(毫秒)，可选
  /// [properties] 要查询的属性列表，多个用逗号分隔
  /// [pageSize] 每页记录数，默认100
  /// [pageNum] 页码，从1开始
  Future<Map<String, dynamic>> getDevicePropertiesHistory({
    required String deviceSn,
    int? startTime,
    int? endTime,
    String? properties,
    int pageSize = 100,
    int pageNum = 1,
  }) async {
    try {
      final Map<String, dynamic> params = {
        'deviceSn': deviceSn,
        'pageSize': pageSize,
        'pageNum': pageNum,
      };

      // 只有当提供了时间参数时才添加到请求中
      if (startTime != null) {
        params['startTime'] = startTime;
      }
      
      if (endTime != null) {
        params['endTime'] = endTime;
      }

      if (properties != null && properties.isNotEmpty) {
        params['properties'] = properties;
      }

      print('设备属性历史查询参数: $params');
      try {
        final response = await _httpClient.get(
          '/connect/api/device/properties/history',
          params: params,
        );
        return response;
      } catch (dioError) {
        // 检查异常对象
        if (dioError is DioException) {
          print('Dio错误类型: ${dioError.type}');
          print('Dio错误消息: ${dioError.message}');
          
          // 检查是否有响应数据
          if (dioError.response != null) {
            print('响应状态码: ${dioError.response?.statusCode}');
            
            // 如果状态码是200，但仍然有Dio错误（可能是响应数据过大）
            if (dioError.response?.statusCode == 200 && dioError.response?.data != null) {
              print('状态码为200但仍有Dio错误，尝试手动处理响应数据');
              
              final responseData = dioError.response?.data;
              
              // 检查响应数据类型
              print('响应数据类型: ${responseData.runtimeType}');
              
              // 如果是Map类型，则是有效的JSON响应
              if (responseData is Map<String, dynamic>) {
                print('响应数据是有效的Map，直接返回');
                return responseData;
              }
              
              // 如果是String类型，尝试解析为JSON
              if (responseData is String) {
                print('尝试解析String类型的响应数据为JSON');
                try {
                  final jsonData = json.decode(responseData);
                  if (jsonData is Map<String, dynamic>) {
                    return jsonData;
                  }
                } catch (e) {
                  print('解析响应数据为JSON失败: $e');
                }
              }
            }
          }
        }
        
        print('设备属性历史查询异常: $dioError');
        throw dioError;
      }
    } catch (e) {
      print('设备属性历史查询失败: $e');
      
      // 如果是已知的DioException且已经被处理过，返回空Map
      if (e is DioException && e.response?.statusCode == 200) {
        return {'list': [], 'total': 0, 'pageSize': pageSize, 'pageNum': pageNum};
      }
      
      rethrow;
    }
  }
} 